#include <head.h>

pthread_mutex_t mutex;
//条件变量
pthread_cond_t cond;
//标记
int flag = 0;

//生成数量
int num = 0;
void * Producer_Func(void * arg){
    while (1)
    {
        sleep(1);
        pthread_mutex_lock(&mutex);
        printf("生产者生产一个产品\n");
        num++;
        flag = 1;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
    

}
void * Consumer_Func(void * arg){
    while(1){
        pthread_mutex_lock(&mutex);
        while(flag == 0){
            pthread_cond_wait(&cond,&mutex);
        }
        printf("消费者消费1个产品\n");
        
        num--;
        printf("num = %d\n",num);
        flag = 0;
        pthread_mutex_unlock(&mutex);
    }

}
void * Consumer1_Func(void * arg){
    while(1){
        pthread_mutex_lock(&mutex);
        while(flag == 0){
            pthread_cond_wait(&cond,&mutex);
        }
        printf("消费者消费n个产品\n");
        
        num--;
        printf("num = %d\n",num);
        flag = 0;
        pthread_mutex_unlock(&mutex);
    }

}

int main(int argc, char const *argv[])
{
    //初始化互斥锁
    pthread_mutex_init(&mutex,NULL);
    //初始化条件变量
    pthread_cond_init(&cond,NULL);
    //定义线程的变量
    pthread_t tid1,tid2,tid3;
    //创建生产者线程
    pthread_create(&tid1,NULL,Producer_Func,NULL);
    pthread_create(&tid2,NULL,Consumer_Func,NULL);
    pthread_create(&tid3,NULL,Consumer1_Func,NULL);
    //回收线程
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);

    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
    //销毁条件变量
    pthread_cond_destroy(&cond);
    return 0;
}